package batch.process.checker;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import batch.process.checker.helper.DueDateCheckerHelper;
import batch.process.core.BaseThread;
import batch.process.utils.BatchProcessUtils;
import batch.process.utils.Constant;

public class DueDateChecker extends BaseThread {

	private DueDateCheckerHelper helper = null;
	
	public DueDateChecker(CountDownLatch finalizado) {
		super(finalizado);
	}
	
	public void run() {
		
		this.setName("DueDateChecker");
		logger.info("Initializing Checker main thread run ...",
				DueDateChecker.class);		
		try {		
			while (!finaliza) {
				try {
					logger.info(this.getName() + " thread awake ... " ,DueDateChecker.class);
					
					BatchProcessUtils.loadProperties();
					
					helper = new DueDateCheckerHelper();
					helper.notifyDueDate();					
					helper = null;										
					
					logger.info("Sending " + this.getName() + " thread to sleep for " + 
							Constant.THREAD_SLEEP_TIME + " hours " ,DueDateChecker.class);
					Thread.sleep(Constant.THREAD_SLEEP_TIME*60*60*1000);					
				} catch (InterruptedException e) {				
					e.printStackTrace();										
					logger.error("Error on checker main thread : " + e,
							DueDateChecker.class);
				}
			}			
		} catch (Exception e) {
			logger.error("Error processing thread ..." + e, DueDateChecker.class);
		} finally {
			logger.info("Finalizing Checker main thread in 10 sec ...",DueDateChecker.class);	
			try {
				finalizado.await(10, TimeUnit.SECONDS);
			} 
			catch (InterruptedException e1) {				
				e1.printStackTrace();
				logger.error("Error upon shutting down Checker main thread :" + e1,
						DueDateChecker.class);
			}
			
			// finaliza as threads de copia			
			logger.info("Due date checker main thread terminated. Shutting down ...",
					DueDateChecker.class);
			super.run();
		}
	}

}
